package com.yanchangapp.ui.activity.mail;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.luck.picture.lib.tools.ScreenUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.util.ui.StatusBarHelper;
import com.zxl.baselib.util.ui.UIUtils;
import com.zxl.baselib.util.window.KeyboardHelper;
import com.yanchangapp.R;
import com.yanchangapp.adapter.MailSearchAdapter;
import com.yanchangapp.commom.AppConstant;
import com.yanchangapp.commom.MailType;
import com.yanchangapp.model.bean.MailItemBean;
import com.yanchangapp.ui.presenter.SearchAtPresenter;
import com.yanchangapp.ui.view.SearchAtView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.functions.Consumer;

/**
 * 邮件搜索页面....
 * refreshLayout.autoRefresh() 触发自动刷新功能
 * 页面跳转,进行已读未读的设置
 * 广播监听进行查看的刷新等...
 */
public class MailSearchActivity extends BaseActivity<SearchAtView, SearchAtPresenter> implements SearchAtView {

    @BindView(R.id.etSearchText)
    EditText etSearchText;
    @BindView(R.id.tvCancel)
    TextView tvCancel;
    @BindView(R.id.rvSearch)
    RecyclerView rvSearch;
    @BindView(R.id.ivDelete)
    ImageView mIvDelete;
    @BindView(R.id.btnNextRefresh)
    TextView btnNextRefresh;
    @BindView(R.id.llErrorNetwork)
    LinearLayout llErrorNetwork;
    @BindView(R.id.llEmptyMail)
    LinearLayout llEmptyMail;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private MailType mMailType;
    private MailSearchAdapter mMailSearchAdapter;
    private static final String MAIL_TYPE = "MAIL_TYPE";
    private static final String TAG = "MailSearchActivity";
    private List<MailItemBean> mTargetLists;
    private int currentPage;
    private String mCurrentKeywords;
    @Override
    protected void init() {
        mTargetLists = new ArrayList<>();
        currentPage = 1;
        if (getIntent() != null) {
            mMailType = (MailType) getIntent().getSerializableExtra(MAIL_TYPE);
        }
    }

    public static void show(Activity activity, MailType mailType) {
        Intent intent = new Intent(activity, MailSearchActivity.class);
        intent.putExtra(MAIL_TYPE, mailType);
        activity.startActivity(intent);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_mail_search;
    }

    @Override
    protected SearchAtPresenter createPresenter() {
        return new SearchAtPresenter(this);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        // 设置状态栏颜色为黑色
        StatusBarHelper.setStatusBarLightMode(this);
        etSearchText.setHint(mMailType.getMailDetail().getSearchTitle());
        initRvAdapter();
        initLoadMore();
        hasContentState();
    }

    // 进行列表的初始化
    private void initRvAdapter() {
        rvSearch.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        rvSearch.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, ScreenUtils.dip2px(this, 0.5f), ContextCompat.getColor(this, R.color.borderColorBase)));
        mMailSearchAdapter = new MailSearchAdapter(R.layout.item_mail_list_content, mTargetLists);
        rvSearch.setAdapter(mMailSearchAdapter);
    }

    // 加载更多初始化
    private void initLoadMore() {
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadMore(true);
    }

    // 有内容的情况
    private void hasContentState(){
        if (rvSearch.getVisibility() == View.GONE){
            rvSearch.setVisibility(View.VISIBLE);
            llEmptyMail.setVisibility(View.GONE);
            llErrorNetwork.setVisibility(View.GONE);
        }
    }



    // 错误情况
    private void errState(){
        if (llErrorNetwork.getVisibility() == View.GONE){
            rvSearch.setVisibility(View.GONE);
            llEmptyMail.setVisibility(View.GONE);
            llErrorNetwork.setVisibility(View.VISIBLE);
        }
    }

    // 空界面
    private void emptyState(){
        if (llEmptyMail.getVisibility() == View.GONE){
            rvSearch.setVisibility(View.GONE);
            llEmptyMail.setVisibility(View.VISIBLE);
            llErrorNetwork.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initData() {

    }

    // 刷新数据
    private void refreshData(String keywords) {
        // 重置底部刷新
        gotoFirst();
        hasContentState();
        // 设置空布局...
        mMailSearchAdapter.setCurrentKeyWords(mCurrentKeywords);
        refreshLayout.setNoMoreData(false);
        refreshLayout.setEnableLoadMore(false);
        currentPage = 1;
        mPresenter.querySearchList(mMailType.getMailDetail().getNetState(), keywords, currentPage);
    }

    private void gotoFirst(){
        rvSearch.scrollToPosition(0);
        LinearLayoutManager mLayoutManager =
                (LinearLayoutManager) rvSearch.getLayoutManager();
        mLayoutManager.scrollToPositionWithOffset(0, 0);
    }

    // 加载更多数据
    private void loadMoreData(String keywords) {
        currentPage++;
        mPresenter.querySearchList(mMailType.getMailDetail().getNetState(), keywords, currentPage);
    }

    private void clearDataWithRf() {
        mTargetLists.clear();
        mMailSearchAdapter.notifyDataSetChanged();
    }

    @Override
    protected void initListener() {
        tvCancel.setOnClickListener(v -> {
            KeyboardHelper.hideKeyboard(tvCancel);
            MailSearchActivity.this.finish();
        });

        mIvDelete.setOnClickListener(v -> etSearchText.setText(""));

        etSearchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            /**
             * 当搜索框的文字变化时回调此方法
             * @param s
             * @param start
             * @param before
             * @param count
             */
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mCurrentKeywords = s.toString();
                if (s.toString().length() == 0) {
                    hideDeleteArrow();
                    clearDataWithRf();
                    refreshLayout.setEnableLoadMore(false);
                } else {
                    showDeleteArrow();
                    refreshData(mCurrentKeywords);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        refreshLayout.setOnLoadMoreListener(refreshLayout -> UIUtils.postTaskDelay(() -> loadMoreData(mCurrentKeywords),1000));

        mMailSearchAdapter.setOnItemClickListener((adapter, view, position) -> {
            int id = mTargetLists.get(position).getId();
            int seenFlag = mTargetLists.get(position).getSeenFlag();
            if (mMailType != MailType.DRAFT){
                if ((seenFlag == AppConstant.MAIL_UN_READ) && (MailType.SENT != mMailType)){
                    mTargetLists.get(position).setSeenFlag(AppConstant.MAIL_HAS_READ);
                    mMailSearchAdapter.notifyItemChanged(position);
                }
                MailDetailActivity.show(MailSearchActivity.this,id,mMailType.getMailDetail().getDescription(),true);
            }else {
                TranspondActivity.showFromDraft(MailSearchActivity.this,id,false);
            }
        });

        mRxManager.on(AppConstant.NOTIFY_SEARCH_DELETE_SUCCESS, (Consumer<Boolean>) aBoolean -> {
            if (aBoolean){
                refreshData(mCurrentKeywords);
            }
        });

        mRxManager.on(AppConstant.NOTIFY_SEARCH_WRITE_SUCCESS, (Consumer<Boolean>) aBoolean -> {
            if (aBoolean){
                refreshData(mCurrentKeywords);
            }
        });

        mRxManager.on(AppConstant.NOTIFY_SEARCH_SAVE_DRAFT_SUCCESS, (Consumer<Boolean>) aBoolean -> {
            if (aBoolean){
                refreshData(mCurrentKeywords);
            }
        });
    }

    private void hideDeleteArrow() {
        if (mIvDelete.getVisibility() == View.VISIBLE) {
            mIvDelete.setVisibility(View.INVISIBLE);
        }
    }

    private void showDeleteArrow() {
        if (mIvDelete.getVisibility() == View.INVISIBLE) {
            mIvDelete.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 搜索回调事件
     * currentPage == 1     代表着列表刷新
     * 其他   代表加载更多
     *
     * @param mList
     */
    @Override
    public void querySearchListSuccess(List<MailItemBean> mList,String keywords) {
        refreshLayout.setEnableLoadMore(true);
        if (!keywords.equals(mCurrentKeywords)){
            mTargetLists.clear();
            mMailSearchAdapter.notifyDataSetChanged();
            return;
        }
        if (mList != null && mList.size() == 0) {
            if (currentPage == 1) {
                // 空页面
                mTargetLists.clear();
                mMailSearchAdapter.notifyDataSetChanged();
                emptyState();
            } else {
                currentPage--;
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        } else {
            if (currentPage == 1) {
                // 进行刷新
                mTargetLists.clear();
                mTargetLists.addAll(mList);
                mMailSearchAdapter.notifyDataSetChanged();
            } else {
                // 加载更多且有数据
                mTargetLists.addAll(mList);
                mMailSearchAdapter.notifyDataSetChanged();
                refreshLayout.finishLoadMore();
            }
        }
    }

    @Override
    public void querySearchListFailure(String err) {
        refreshLayout.setEnableLoadMore(true);
        errState();
        UIUtils.showToast(err);
        currentPage--;
    }
}
